// 这是一个可选的Node.js后端实现，提供更可靠的云列表服务
// 需要安装: npm install express cors body-parser

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;
const DATA_FILE = path.join(__dirname, 'cloud-data.json');

// 确保数据文件存在
if (!fs.existsSync(DATA_FILE)) {
    fs.writeFileSync(DATA_FILE, JSON.stringify({}));
}

// 读取数据
function readData() {
    try {
        const data = fs.readFileSync(DATA_FILE, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('读取数据错误:', error);
        return {};
    }
}

// 保存数据
function saveData(data) {
    try {
        fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
    } catch (error) {
        console.error('保存数据错误:', error);
    }
}

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '.')));

// API路由
app.get('/api/ping', (req, res) => {
    res.json({
        success: true,
        message: "连接成功",
        serverTime: Date.now()
    });
});

app.post('/api/save', (req, res) => {
    const { projectId, listName, items } = req.body;
    const data = readData();
    
    if (!projectId || !listName || !Array.isArray(items)) {
        return res.json({ success: false, message: "参数错误" });
    }
    
    if (!data[projectId]) data[projectId] = {};
    data[projectId][listName] = {
        items: [...items],
        timestamp: Date.now()
    };
    
    saveData(data);
    res.json({ success: true, message: "列表保存成功" });
});

app.get('/api/load', (req, res) => {
    const { projectId, listName } = req.query;
    const data = readData();
    
    if (!projectId || !listName) {
        return res.json({ success: false, message: "参数错误" });
    }
    
    const list = data[projectId]?.[listName];
    if (!list) {
        return res.json({ success: false, message: "列表不存在" });
    }
    
    res.json({ success: true, items: list.items });
});

app.post('/api/add', (req, res) => {
    const { projectId, listName, item } = req.body;
    const data = readData();
    
    if (!projectId || !listName || item === undefined) {
        return res.json({ success: false, message: "参数错误" });
    }
    
    if (!data[projectId]) data[projectId] = {};
    if (!data[projectId][listName]) {
        data[projectId][listName] = { items: [], timestamp: Date.now() };
    }
    
    data[projectId][listName].items.push(item);
    data[projectId][listName].timestamp = Date.now();
    
    saveData(data);
    res.json({
        success: true,
        message: "项已添加",
        newLength: data[projectId][listName].items.length
    });
});

app.post('/api/remove', (req, res) => {
    const { projectId, listName, index } = req.body;
    const data = readData();
    
    if (!projectId || !listName || index === undefined) {
        return res.json({ success: false, message: "参数错误" });
    }
    
    const list = data[projectId]?.[listName];
    if (!list || index < 0 || index >= list.items.length) {
        return res.json({ success: false, message: "索引无效" });
    }
    
    list.items.splice(index, 1);
    list.timestamp = Date.now();
    
    saveData(data);
    res.json({
        success: true,
        message: "项已删除",
        newLength: list.items.length
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`TurboWarp云列表服务运行在 http://localhost:${PORT}`);
});
    